<?php
class System_UserController extends Apps_Controller_Action {
// Default UserId
	const DEFAULT_USER_ID = 1;

	public function indexAction() {
		$this->_redirect('/system/user/list/');
	}
	/*
	 * Show list user
	 */
	public function listAction() {
		$this->actResolve('act_delete',
				'delete', 'user', 'system', array('id' => $this->_getParam('item_checker')),
				true);
		$q = $this->_dbAdapter
				  ->select()
				  ->from('user', null)
				  ->join('user_group', 'user_group.id = user.user_group_id')
				  ->columns(array(
				      'id' 				=> 'user.id',
				  	  'username' 		=> 'user.username',
				  	  'full_name' 		=> 'user.full_name',
				  	  'group_name' 		=> 'user_group.name',
				  	  'phone'			=> 'user.phone',
				  	  'email'			=> 'user.email',
				  	  'address'			=> 'user.address',
				  	  'description' 	=> 'user.description',
					  'created_date' 	=> 'user.created_date'
				  ));

		$grid = new Apps_Plugin_Grid('user');
		$grid->setData($q)
			 ->setTableColumnFormat(array(
			     array(
			         'title' 		=> 'ID',
			     	 'dataField'	=> 'id'
			     ),
			     array(
			         'title' 		=> 'Tên đăng nhập',
			     	 'dataField'	=> 'username'
			     ),
			     array(
			         'title' 		=> 'Họ tên',
			     	 'dataField'	=> 'full_name'
			     ),
			     array(
			         'title' 		=> 'Chức vụ',
			     	 'dataField'	=> 'group_name'
			     ),
			     array(
			         'title' 		=> 'Điện thoại',
			     	 'dataField'	=> 'phone'
			     ),
			     array(
			         'title' 		=> 'Email',
			     	 'dataField'	=> 'email'
			     ),
			     array(
			         'title' 		=> 'Địa chỉ',
			     	 'dataField'	=> 'address'
			     ),
			     array(
			         'title' 		=> 'Ghi chú',
			     	 'dataField'	=> 'description'
			     ),
			     array(
			         'title' 		=> 'Ngày tạo',
			     	 'dataField'	=> 'created_date'
			     ),
			 	array('title'      =>  'Sửa',
			 		  'html'       =>  array('<a href="/system/user/edit?id=%s"><i class="icon-edit" title="Sửa" ></i></a>', array('id')),
			 		  'width'	   => '2%'
			 	),
			 	array('title'      =>  'Xóa',
			 		  'html'       =>  array('<a href="/system/user/delete?id=%s">
					 		  				 <i class="icon-remove must-confirm" title="Xóa" data-must-confirm-msg="Xóa người dùng khỏi hệ thống" ></i></a>',
					 		  				 array('id')),
			 		  'width'	   => '2%'
			 	)
			 ));
		$this->view->grid = $grid;
	}

	public function addAction() {
		$rq   = $this->_request;
        $form = new F_Management_UserAdd();
        if($rq->isPost()) {
        	$tbUser = new M_DbTable_User();
            if($form->isValid($rq->getParams())) {
            	$d = $form->getValues();
            	$d['password'] = md5($d['password']);
            	unset($d['passwordConfirm']);
            	$r = $tbUser->safelyInsert($d);
                $this->_flashMessenger->addMessage(
                	$r
                    ? self::$msgAddSuccess
                    : self::$msgAddFailed);
                return $this->goToIndexAction();
            }
        }

        $this->view->form = $form;
	}

	public function editAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');
        $form = new F_Management_UserEdit();
        $tbUser = new M_DbTable_User();

		if(!$id || !($r = $tbUser->fetchRow(array('id=?' => $id))->toArray())) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
            return $this->goToIndexAction();
        }

        if($rq->isPost()) {
            if($form->isValid($rq->getParams())) {
            	$d = $form->getValues();
            	$d['password'] = md5($d['password']);
            	unset($d['passwordConfirm']);
            	$r = $tbUser->safelyUpdate($d, array('id = ?' => $id));
                $this->_flashMessenger->addMessage(
                    $r
                    ? self::$msgUpdateSuccess
                    : self::$msgUpdateFailed);
                return $this->goToIndexAction();
            }
        } else {
            $form->populate($r);
        }

        $this->view->form = $form;
	}

	public function deleteAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$userIds = $rq->getParam('id');
		if(!$userIds) {
			$this->goToIndexAction();
		}
		$tbUser   = new M_DbTable_User();
		if(is_array($userIds)) {
			foreach ($userIds as $userId) {

				// User_Default cannot delete
					if($userId == self::DEFAULT_USER_ID) {
						$this->_flashMessenger->addMessage(self::$msgDeleteError);
						return $this->goToIndexAction();
					}

				$r = $tbUser->delete(array('id = ?' => $userId));
			}
			$this->goToIndexAction();
		} elseif (is_numeric($userIds)) {

			// User_Default cannot delete
				if($userIds == self::DEFAULT_USER_ID) {
					$this->_flashMessenger->addMessage(self::$msgDeleteError);
					return $this->goToIndexAction();
				}

			$r = $tbUser->delete(array('id = ?' => $userIds));
			$this->_flashMessenger->addMessage($r ? self::$msgDeleteSuccess : self::$msgDeleteError);
			$this->goToIndexAction();
		} else {
			$this->goToIndexAction();
		}
	}

}
